import * as vscode from "vscode";

import { ApiConfiguration } from "./apiHandler";
import { Task } from "./task";

export class AgentWebviewProvider implements vscode.WebviewViewProvider {
  private webview: vscode.Webview | undefined;
  private currentTask: Task | undefined = undefined;
  private apiConfiguration: ApiConfiguration = {
    model: "gpt-4.1",
    apiKey: "any-key",
    baseUrl: "https://litellm.unboundwill.com/v1",
  };
  constructor(readonly context: vscode.ExtensionContext) {}

  resolveWebviewView(
    webviewView: vscode.WebviewView,
    context: vscode.WebviewViewResolveContext,
    token: vscode.CancellationToken
  ): Thenable<void> | void {
    this.webview = webviewView.webview;

    webviewView.webview.options = {
      enableScripts: true,
    };

    const scriptUri = webviewView.webview.asWebviewUri(
      vscode.Uri.joinPath(
        this.context.extensionUri,
        "agent-webview",
        "dist",
        "assets",
        "index.js"
      )
    );

    webviewView.webview.html = `
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Vite + React + TS</title>
    <script type="module" crossorigin src=${scriptUri}></script>
  </head>
  <body>
    <div id="root"></div>
  </body>
</html>
    `;

    webviewView.webview.onDidReceiveMessage((message: string) => {
      vscode.window.showInformationMessage(message);
      this.currentTask = new Task(this, this.apiConfiguration, message);
      this.currentTask.start();
    });
  }

  postMessage(message: string) {
    this.webview?.postMessage(message);
  }
}
